import CryptoJS from "crypto-js";

const secretKey = "war3secretscriptstrengthandhonor";

// 不加密的接口
const noEncryptionUrl = ['/api/terminal/machine/type/gigNamePage', '/api/terminal/machine/job/gigJobPage',
	'/api/terminal/machine/job'
]
// 

// AES加密函数
function aesEncrypt(text, key) {
	if (typeof text === 'object' && text !== null) {
		// 检查输入是否为对象，如果是则转换为字符串
		text = JSON.stringify(text);
	}

	const keyUtf8 = CryptoJS.enc.Utf8.parse(key);
	const encrypted = CryptoJS.AES.encrypt(text, keyUtf8, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7, // PKCS5Padding在CryptoJS中对应的是Pkcs7
	});
	console.log('text', encrypted.toString());
	return encrypted.toString();
}

// AES解密函数
function aesDecrypt(ciphertext, key) {
	const keyUtf8 = CryptoJS.enc.Utf8.parse(key);
	const decrypted = CryptoJS.AES.decrypt(ciphertext, keyUtf8, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7, // PKCS5Padding在CryptoJS中对应的是Pkcs7
	});
	return CryptoJS.enc.Utf8.stringify(decrypted);
}

// Base64编码函数
function base64Encode(input) {
	return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(input));
}

// Base64解码函数
function base64Decode(input) {
	return CryptoJS.enc.Utf8.stringify(CryptoJS.enc.Base64.parse(input));
}

export const sendRequest = (target, config) => {
	if (!target.url) throw new Error("url地址不能为空");
	let result = null;
	let method = target.method.toUpperCase();
	switch (method) {
		case "POST":
		case "GET":
		case "PUT":
			result = target.data;
			break;
		case "DELETE":
			target.url = target.url + "/" + target.data;
			break;
	}
	return new Promise((resolve, reject) => {
		let json = {
			url: target.url,
			data: result,
			method: method,
			...config,
		};
		// console.log('json.url', json);
		const {
			token
		} = uni.getStorageSync("token");
		// console.log("token", token);
		json.header = {
			Authorization: token,
		};


		// 有值  且  在加密的接口数组中
		if (json.data && !noEncryptionUrl.includes(target.url)) {
			const encryptedData = aesEncrypt(json.data, secretKey);
			json.data = {
				data: encryptedData
			};
		}


		return uni.request({
			...json,
			success: function(res) {
				if (res.statusCode === 500) {
					uni.showToast({
						title: res.data || "服务器响应超时",
						icon: "none"
					});
					setTimeout(function() {
						uni.reLaunch({
							url: "/pages/home/index"
						});
					}, 500);
				}
				let data = res.data;
				switch (data.code) {
					case 500:
						uni.showToast({
							icon: "none",
							title: data.message || "系统错误"
						});
						reject(data);
						break;
					case 200:
						// 解密响应数据
						if (data.data) {
							console.log('data');
							const decryptedText = aesDecrypt(data.data, secretKey);
							console.log('decryptedText');
							resolve({
								...data,
								data: JSON.parse(decryptedText)
							});
						} else {
							resolve(data);
						}
						break;
					case 401:
						uni.showToast({
							title: data.message,
							icon: "none"
						});
						setTimeout(function() {
							uni.reLaunch({
								url: "/pages/home/index"
							});
						}, 500);
						break;
					case 601:
						uni.showToast({
							title: data.msg,
							icon: "none"
						});
						break;
				}
			},
			fail(err) {
				uni.showToast({
					title: "请求数据异常",
					icon: "none",
				});
				throw new Error(err.errMsg);
			},
		});
	});
};

// 上传图片
export const sendUpload = async (url, filePath, file) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: url,
			filePath: filePath,
			file: file,
			name: "file",
			success: (res) => {
				let data = JSON.parse(res.data);
				resolve(data);
			},
			fail(err) {
				console.log("err", err);
				reject(err);
			},
		});
	});
};

// 上传图片(多个)
export const sendUploads = async (url, fileList) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: url,
			files: fileList,
			success: (res) => {
				let data = JSON.parse(res.data);
				resolve(data);
			},
			fail(err) {
				console.log("err", err);
				reject(err);
			},
		});
	});
};

export default {
	sendRequest,
	sendUpload,
	sendUploads,
};